package org.tio.sitexxx.web.server.controller.gl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpMaterialServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.http.common.HttpRequest;
import org.tio.http.server.annotation.RequestPath;
import org.tio.sitexxx.service.model.main.Knowledge;
import org.tio.sitexxx.service.service.qj.KnowledgeService;
import org.tio.sitexxx.service.vo.Const;
import org.tio.sitexxx.web.server.utils.WxMpProperties;
import org.tio.utils.resp.Resp;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 编码:tanLin
 * 2019/7/27
 */
@RequestPath("/wx")
public class WxController {
    private static final WxController wxController=new WxController();
    public static WxController getInstance(){//懒汉式单例
        return wxController;
    }
    private static Logger log = LoggerFactory.getLogger(WxController.class);
    //获取永久素材
    private static final String getForverPath = "https://api.weixin.qq.com/cgi-bin/material/get_material";
    private static String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    private static WxMpService wxMpServices;
    private static WxMpMaterialService wxMpMaterialService;
    private static WxMpProperties wxMpProperties = new WxMpProperties();
    private static final OkHttpClient client = new OkHttpClient();
    private static WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();

    static {
        wxMpServices = new WxMpServiceImpl();
        config.setAppId(wxMpProperties.getAppId()); // 设置微信公众号的appid
        config.setSecret(wxMpProperties.getSecret()); // 设置微信公众号的app corpSecret
    }

    /**
     * 获取token  主要用途是每次请求之前更新一次token
     *
     * @throws IOException
     */
    private static void getToken() throws IOException {
        String APPID = wxMpProperties.getAppId();
        String APPSECRET = wxMpProperties.getSecret();
        String request_url = TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        Request request = new Request.Builder().url(request_url).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            System.out.println(jsonObject);
            if (null != jsonObject) {
                String access_tocken = jsonObject.getString("access_token");
                System.out.println("token:" + access_tocken);
                wxMpProperties.setToken(access_tocken);//请求一次更新一次token
            }
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 素材管理的相关接口，包括媒体管理的接口   初始化， WxMpMaterialService
     *
     * @throws IOException
     */
    public void wx() throws IOException {
        getToken();
        config.setToken(wxMpProperties.getToken()); // 设置微信公众号的token
        config.setAesKey("a9cNqnFo0mThG7hbKKZXsRSbt3gr5PZsrcknvsgz8bj"); // 设置微信公众号的EncodingAESKey
        wxMpServices.setWxMpConfigStorage(config);
        wxMpMaterialService = new WxMpMaterialServiceImpl(wxMpServices);

    }

    /**
     * get方法
     *
     * @param echostr
     * @return
     */
    @RequestPath("/get/msg")
    public Object news(HttpRequest request, String echostr) {
        Map<String, Object[]> map = request.getParams();
        System.out.println("test:" + JSON.toJSONString(map));
        System.out.println("echostr:" + echostr);
        return echostr;
    }


    /**
     * 图文消息存入数据库
     *
     * @param result
     */
    @SuppressWarnings("unchecked")
    public void post(WxMpMaterialNewsBatchGetResult result) {
        for (WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem s : result.getItems()) {
            WxMpMaterialNews content = s.getContent();
            List<WxMpMaterialNews.WxMpMaterialNewsArticle> articles = content.getArticles();
            WxMpMaterialNews.WxMpMaterialNewsArticle article = articles.get(0);
            Map<String, Object> map = new HashedMap();//去重的参数
            map.put("media_id", s.getMediaId());
            if(KnowledgeService.me.getKnowledge(map)==null){//生成对应的对象
                Record know=new Record().set("clicks",0).set("brief",article.getDigest()).set("category","article").set("content_url",article.getUrl())
                        .set("image",article.getThumbUrl()).set("media_id",s.getMediaId()).set("style","").set("title",article.getTitle())
                        .set("createdAt",new Date()).set("updatedAt",new Date());
                Db.use(Const.Db.TIO_SITE_MAIN).save("knowledge",know);
            }
            /*try {
                WxMpMaterialNews wxMpMaterialNews=wxMpMaterialService.materialNewsInfo(s.getMediaId());
                List<WxMpMaterialNews.WxMpMaterialNewsArticle> list=wxMpMaterialNews.getArticles();
                list.forEach(wxMpMaterialNewsArticle -> {
                    System.out.println("永久图文信息:"+ JSON.toJSONString(wxMpMaterialNewsArticle));
                });
            } catch (WxErrorException e) {
                e.printStackTrace();
            }*/
            System.out.println("s:" + JSON.toJSONString(s));
        }
        System.out.println("pull finish.......");
    }

    /**
     * https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738734
     * https://github.com/Wechat-Group/WxJava/wiki/MP_%E6%B0%B8%E4%B9%85%E7%B4%A0%E6%9D%90%E7%AE%A1%E7%90%86
     *
     * @throws WxErrorException
     * @throws IOException
     */
    @RequestPath("/msg")//素材存入数据库
    public void put() throws WxErrorException, IOException {
        wx();
        int offset = 0;
        int count = 3;
        int size = count;
        while (size == 3) {//循环拉去
            /**
             * 偏移位置 int offset 从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
             * 返回数量 int count 取值在1到20之间
             *
             * java.lang.NoSuchFieldError: deserializationContext
             */
            WxMpMaterialNewsBatchGetResult result = wxMpMaterialService.materialNewsBatchGet(offset, count);
            offset += count;
            size = result.getItems().size();
            post(result);
        }

    }

    /**
     * 获取广告
     * @return
     */
    @RequestPath("/getAds")
    public List<Knowledge> getAds(){
        return KnowledgeService.me.getAd();
    }

    /**
     * 获取文章
     * @param start
     * @param paginate
     * @return
     */
    @SuppressWarnings("all")
    @RequestPath("/getArticle")
    public Page<Knowledge> getArticle(Integer start, Integer paginate){
        if(start==null||paginate==null) return new Page<Knowledge>();
        return KnowledgeService.me.getArticle(start,paginate);
    }

    /**
     * 文章转为小程序上的广告展示
     * @param request request
     * @return
     */
    @RequestPath("/change")
    public Resp change(HttpRequest request){
        int id = request.getInt("id");
        Map <String,Object>m = new HashMap<String,Object>();
        int ok;
        m.put("id",id);
        System.out.println("id"+id);
        Knowledge k = KnowledgeService.me.getKnowledge(m);
        System.out.println(k.getCategory());
        if(k.getCategory().equals("ads")){
            ok = 1;
            k.setCategory("article");
        }else if(k.getCategory().equals("article")){
            ok = 1;
            k.setCategory("ads");
        }else {
            ok = 0;
        }
        KnowledgeService.me.update(k);
        m.put("ok",ok);
        return Resp.ok(m);
    }

    /**
     * 删除推送
     * @param request request
     * @return  Resp
     */
    @RequestPath("/del")//删除推送
    public Resp del(HttpRequest request){
        Map<String,Object> m = new  HashMap<String,Object>();
        m.put("id",request.getInt("id"));
        Knowledge k = KnowledgeService.me.getKnowledge(m);
        if(null==k||null==k.getId())return Resp.fail();
        KnowledgeService.me.deleteById(k);
        return Resp.ok();
    }

    /**
     * 添加公告
     * @param request
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    @RequestPath("/add")
    public Resp add(HttpRequest request) {
        Map<String,Object>map= JSON.parseObject(request.getBodyString());
        try{
            Knowledge k= JSON.parseObject(JSON.toJSONString(map),Knowledge.class);
            k.setCategory("text");
            Date date=new Date();
            k.setCreatedAt(date);
            k.setUpdatedAt(date);
            KnowledgeService.me.save(k);
            return Resp.ok();
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return Resp.fail("参数错误");
    }

    /**
     * 获取公告
     * @param start pageNum
     * @param paginate PageSize
     * @return
     */
    @RequestPath("/getNotice")
    public Resp getNotice(Integer start,Integer paginate){
        System.out.println(start+" "+paginate);
        if(start==null||paginate==null)return Resp.fail();
        Page<Knowledge> list=KnowledgeService.me.getNotices(start,paginate);
        System.out.println("list:"+JSON.toJSONString(list));
        if(list==null){
            return Resp.ok("暂无公告");
        }
        return Resp.ok(list);
    }

    /**
     * 改变类型
     * @param request request
     * @return Resp
     */
    @RequestPath("/modify")
    public Resp modity(HttpRequest request){
        try{
            Map<String,Object>map= JSON.parseObject(request.getBodyString());

            Integer id =Integer.valueOf(map.get("id").toString());
            Map <String,Object> m = new  HashMap<String,Object>();
            m.put("id",id);
            Knowledge knowledge=KnowledgeService.me.getKnowledge(m);

            if(knowledge.getCategory().equals("notice")){
                knowledge.setCategory("text");
            }else{
                knowledge.setCategory("notice");
            }
            KnowledgeService.me.update(knowledge);
            return Resp.ok(knowledge);
        }catch (Exception e){
            log.error(e.toString(),e);
        }
        return Resp.fail();
    }




}


